package com.kerbores.blog.dao.impl;

import java.util.List;

import org.nutz.dao.Condition;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;

import com.kerbores.blog.bean.Article;
import com.kerbores.blog.dao.IArticleDao;
import com.kerbores.utils.db.dao.impl.BaseDao;

/**
 * @author 贵源 <br>
 *         create at 2014年10月21日
 */
@IocBean(name = "articleDao")
public class ArticleDaoImpl extends BaseDao<Article> implements IArticleDao {

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.utils.db.dao.impl.BaseDao#initClass()
	 */
	@Override
	public Class<Article> initClass() {
		return Article.class;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.utils.db.dao.impl.BaseDao#findAll()
	 */
	@Override
	public List<Article> findAll() {
		return fill(super.findAll());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.utils.db.dao.impl.BaseDao#findAll(java.lang.String)
	 */
	@Override
	public List<Article> findAll(String orderby) {
		return fill(super.findAll(orderby));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.kerbores.utils.db.dao.impl.BaseDao#findByCondition(org.nutz.dao.Condition
	 * )
	 */
	@Override
	public Article findByCondition(Condition condition) {
		return fill(super.findByCondition(condition));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.utils.db.dao.impl.BaseDao#findById(int)
	 */
	@Override
	public Article findById(int id) {
		return fill(super.findById(id));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.kerbores.utils.db.dao.impl.BaseDao#search(org.nutz.dao.Condition)
	 */
	@Override
	public List<Article> search(Condition condition) {
		return fill(super.search(condition));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.kerbores.utils.db.dao.impl.BaseDao#searchByPage(org.nutz.dao.Condition
	 * , int, int)
	 */
	@Override
	public List<Article> searchByPage(Condition condition, int currentPage, int pageSize) {
		return fill(super.searchByPage(condition, currentPage, pageSize));
	}

	public Article fill(Article article) {
		dao.fetchLinks(article, "author");
		dao.fetchLinks(article, "catalog");
		return article;
	}

	public List<Article> fill(List<Article> articles) {
		Lang.each(articles, new Each<Article>() {
			@Override
			public void invoke(int index, Article article, int length) throws ExitLoop, ContinueLoop, LoopException {
				dao.fetchLinks(article, "author");
				dao.fetchLinks(article, "catalog");
			}
		});
		return articles;
	}

}
